import {
	ARCHIVES_TYPE,
	ARCHIVES_STATE,
} from '@/const/archives/index.js'
import {
	cutFile
} from './cutFile.js'
import {
	MODULE_DICTID,
	MODULE_DICTID_NAMES
} from '@/const/modules/index.js'
import store from '@/store/index.js'
import {
	getFileAsync,
	getFileEntryAsync,
	getDirEntryAsync,
	getFile,
	writeContextToFileAsync,
	getFileContextAsync,
	iterateDierctory,
	existFileAsync,
	removeFile,
	copyFileToPrivateDoc,
	getOrCreateDirectory,
	getDocRootEntry
} from './loUtil.js'
import timeFormat from '@/uview-ui/libs/function/timeFormat.js'
import md5 from '@/utils/md5.js'

let archivesNameAfter = '/data.txt'
let archivesNameBefore = 'archiveId'

async function getModuleDictNum(archivesId) {
	const dirEntryName = `${archivesNameBefore}_${archivesId}`;
	let entry;
	try {
		entry = await getDirEntryAsync(dirEntryName);
		console.log(entry.name);
	} catch (error) {
		console.error("Error getting directory entry:", error);
		return {}; // 返回空对象或根据实际情况进行错误处理
	}

	let entries = [];
	try {
		entries = await iterateDierctory(entry);
	} catch (error) {
		console.error("Error iterating directory:", error);
		return {}; // 返回空对象或根据实际情况进行错误处理
	}

	const regex = /^evidence_(\d+)_\d+\.txt$/; // 提取正则表达式定义
	const entrysMatchingRegex = entries.filter(entry => regex.test(entry.name));
	const dictIdArr = new Map(); // 使用 Map 以保留插入顺序

	for (const entry of entrysMatchingRegex) {
		const match = entry.name.match(/^evidence_(\d+)/);
		if (match && match.length > 1) {
			const dictId = Number(match[1]);
			console.log(dictId);
			if (dictIdArr.has(dictId)) {
				dictIdArr.set(dictId, dictIdArr.get(dictId) + 1);
			} else {
				dictIdArr.set(dictId, 1);
			}
		}
	}
	console.log(dictIdArr);
	return dictIdArr;
}
// 创建\获取案卷类型 对应的模块列表
export async function getLocalModule(archivesId, archivesType) {
	const fileName = `${archivesNameBefore}_${archivesId}/getModule.txt`
	const flag = await existFileAsync(fileName)
	const simpleModuleIds = [MODULE_DICTID.note, MODULE_DICTID.extract, MODULE_DICTID.loss, MODULE_DICTID
		.evidence, MODULE_DICTID.photo, MODULE_DICTID.accident
	] // 简易火灾
	const commonlyModuleIds = Object.values(MODULE_DICTID) // 一般程序
	const slightModuleIds = [MODULE_DICTID.photo, MODULE_DICTID.accident] // 轻微火灾
	const {
		archivesTypeList
	} = await getBasicInfoFromLocalData()
	if (!Object.keys(archivesTypeList).length) {
		return
	}
	const moduleList = archivesTypeList[archivesType]
	const moduleData = {
		[ARCHIVES_TYPE.SIMPLE]: moduleList.map((item, index) => ({
			name: MODULE_DICTID_NAMES[item.value],
			remark: '',
			fileNum: 0,
			value: item.value,
			noticeId: index + 1
		})),
		[ARCHIVES_TYPE.COMMONLY]: moduleList.map((item, index) => ({
			name: MODULE_DICTID_NAMES[item.value],
			remark: '',
			fileNum: 0,
			value: item.value,
			noticeId: index + 1
		})),
		[ARCHIVES_TYPE.SLIGHT]: moduleList.map((item, index) => ({
			name: MODULE_DICTID_NAMES[item.value],
			remark: '',
			fileNum: 0,
			value: item.value,
			noticeId: index + 1
		}))
	}
	if (!flag) {
		// 创造证据链文件
		await writeContextToFileAsync(fileName, moduleData[archivesType])
		return moduleData[archivesType]
	} else {
		let res = await getFileContextAsync(fileName)
		const localModuleData = JSON.parse(res.result)
		const dictIdMap = await getModuleDictNum(archivesId)
		const newModuleData = moduleData[archivesType]

		const arr = newModuleData.map(item => {
			// console.log(item);
			dictIdMap.forEach((value, dictId) => {
				if (item.value == dictId) {
					item.fileNum = value
				}
			});
			return item
		})
		console.log(arr);
		console.log(localModuleData);
		if (localModuleData.length != arr.length) {
			let combinedArray = arr.map(item => {
				let newItem = localModuleData.find(dataItem => item.value == dataItem.value);
				return newItem ? newItem : item;
			});
			await writeContextToFileAsync(fileName, combinedArray)
			await getLocalNoticeList(archivesId, archivesType)
			return combinedArray
		}
		return localModuleData
	}
}
// 创建\获取 案卷模块下的notice列表
export async function getLocalNoticeList(archivesId, archivesType) {
	let fileName = `${archivesNameBefore}_${archivesId}/evidence_notice.txt`
	let currentEntry;
	let directoryEntries = await iterateDierctory()
	for (const entry of directoryEntries) {
		if (entry.name == `${archivesNameBefore}_${archivesId}`) {
			currentEntry = entry
		}
	}
	let flag = await existFileAsync(fileName, currentEntry)
	let simpleModuleIds = [MODULE_DICTID.note, MODULE_DICTID.extract, MODULE_DICTID.loss, MODULE_DICTID
		.evidence, MODULE_DICTID.photo, MODULE_DICTID.accident
	]
	let commonlyModuleIds = Object.values(MODULE_DICTID)
	let slightModuleIds = [MODULE_DICTID.photo, MODULE_DICTID.accident]
	const {
		archivesTypeList
	} = await getBasicInfoFromLocalData()
	const moduleList = archivesTypeList[archivesType]
	const moduleData = moduleList.map((item, index) => ({
		noticeId: index + 1,
		dictId: item.value,
		mapList: []
	}))
	if (!flag) {
		// 创造证据链文件
		await writeContextToFileAsync(fileName, moduleData)
		return data[archivesType]
	} else {
		let res = await getFileContextAsync(fileName)
		let localModuleData = JSON.parse(res.result)
		const localModuleDataMap = localModuleData.map(module => {
			module.mapList.map((item, index) => {
				return {
					...item,
					keyId: index + 1
				}
			})
			return module
		})
		if (localModuleDataMap.length != moduleData.length) {
			let combinedArray = moduleData.map(item => {
				let newItem = localModuleDataMap.find(dataItem => item.dictId == dataItem.dictId);
				return newItem ? newItem : item;
			});
			await writeContextToFileAsync(fileName, combinedArray)
			return combinedArray
		}
		return localModuleDataMap
	}
}
// 添加\编辑 案卷
export async function createFile(form) {
	if (form.archivesId) {
		const path = `${archivesNameBefore}_${form.archivesId}${archivesNameAfter}`
		// 案卷 写入数据
		await writeContextToFileAsync(path, form)
		return form.archivesId
	} else {
		let time = new Date().getTime()
		const nowFormat = timeFormat(time, 'yyyy-mm-dd hh:MM:ss')
		const path = `${archivesNameBefore}_${time}${archivesNameAfter}`
		// 生成一个0到999的随机数
		const randomNumber = Math.floor(Math.random() * 10000);
		// 将随机数转换为4位字符串
		const randomString = randomNumber.toString().padStart(4, '0');
		const str = `${time}${randomString}`
		const md5Str = md5.hex_md5(str)
		const data = {
			...form,
			state: ARCHIVES_STATE.INVESTIGATE,
			archivesId: time,
			createTime: nowFormat,
			md5: md5Str,
			updateTime: nowFormat,
			pullUpdateTime: null,
			pushUpdateTime: null
		}
		// 创造案卷文件
		await writeContextToFileAsync(path, data)
		await getLocalModule(time, form.archivesType)
		return time
	}
}
// 删除案卷
export async function removeLocalFile(archivesId) {
	return new Promise(resolve => {
		const path = `${archivesNameBefore}_${archivesId}`
		plus.io.resolveLocalFileSystemURL('_doc/' + path, function(entry) {
			entry.removeRecursively(() => {
				resolve()
			})
		}, function(error) {
			console.error('Error resolving directory URL:', error);
		});
	})
}
// 结案归档
export async function closeAndArchiveCase(archivesId, closeBaseForm) {
	const path = `${archivesNameBefore}_${archivesId}/data.txt`
	const res = await getFileContextAsync(path)
	const data = JSON.parse(res.result)
	const closeCaseData = Object.assign(data, closeBaseForm, {
		state: ARCHIVES_STATE.CLOSECASE
	})
	await writeContextToFileAsync(path, closeCaseData)
}
// 查询 案卷列表
export async function getLocalFileList() {
	try {
		const fileList = [];
		const directoryEntries = await iterateDierctory();

		for (const entry of directoryEntries) {
			if (entry.name.includes(archivesNameBefore) && entry.isDirectory) {
				// 拼接文件路径
				const filePath = entry.name + archivesNameAfter;
				fileList.push(getFileContextAsync(filePath));
			}
		}

		// 使用 Promise.all 并发处理文件请求
		const results = await Promise.all(fileList);
		// 解析结果并返回
		return results.map((item) => {
			return item.result ? JSON.parse(item.result) : item.result
		});
	} catch (error) {
		console.error('Error while fetching file list:', error);
		throw error;
	}
}
// 获取案卷详情
export async function getLocalArchivesDetail(archivesId) {
	if (archivesId) {
		let fileName = `${archivesNameBefore}_${archivesId}${archivesNameAfter}`
		let flag = await existFileAsync(fileName)
		if (flag) {
			let res = await getFileContextAsync(fileName)
			let data = JSON.parse(res.result)
			return data
		}
	} else {
		let lastArchivesPath = null
		const directoryEntries = await iterateDierctory();

		for (const entry of directoryEntries) {
			if (entry.name.includes(archivesNameBefore) && entry.name.indexOf('zip') == -1) {
				// 拼接文件路径
				const filePath = entry.name + archivesNameAfter;
				lastArchivesPath = filePath
			}
		}
		let res = await getFileContextAsync(lastArchivesPath)
		let data = JSON.parse(res.result)
		return Promise.resolve(data)
	}
}
// 从本地列表获取指定id的案卷
export async function getSpecificItemFromLocalList(archivesId) {
	let fileName = `${archivesNameBefore}_${archivesId}${archivesNameAfter}`
	let flag = await existFileAsync(fileName)
	if (flag) {
		let res = await getFileContextAsync(fileName)
		let data = JSON.parse(res.result)
		return data
	}
}
// 从本地列表获取最新的案卷
export async function getLatestItemFromLocalList() {
	let lastArchivesPath = null
	const directoryEntries = await iterateDierctory();

	for (const entry of directoryEntries) {
		if (entry.name.includes(archivesNameBefore) && entry.name.indexOf('zip') == -1) {
			// 拼接文件路径
			const filePath = entry.name + archivesNameAfter;
			lastArchivesPath = filePath
		}
	}
	let res = await getFileContextAsync(lastArchivesPath)
	let data = JSON.parse(res.result)
	return Promise.resolve(data)
}
/**
 * 上传文件
 * @param {string} archivesId - 档案ID，用于构建文件上传的本地路径
 * @param {Object} file - 文件对象
 * @param {string} file.url - 文件的URL，用于指定文件的远程位置
 * @param {string} file.name - 文件名，用于指定上传后的文件名
 * @param {string} file.type - 文件后缀名
 * @returns {Promise<string>} - 返回一个 Promise，表示上传后文件在本地的完整路径
 */
export async function uploadLocalFile(archivesId, file) {
	const path = `${archivesNameBefore}_${archivesId}/images`
	let res = await copyFileToPrivateDoc(file.url, path, file.name, file.type)
	return res.fullPath
}
export async function copyFiles(sourceFolder = `${archivesNameBefore}_1695896826475`, destinationFolder =
	`${archivesNameBefore}_cls`) {
	return new Promise(async (resolve, reject) => {
		async function renameFolder(oldPath, newName) {

			// 获取文件夹对象
			let entry = await getDirEntryAsync(sourceFolder)

			var parentPath = oldPath.substring(0, oldPath.lastIndexOf('/'));
			var newFullPath = parentPath + newName;
			plus.io.resolveLocalFileSystemURL(oldPath, function(entry2) {
				plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
					entry2.moveTo(root, newName, function(newEntry) {
						console.info('文件夹重命名成功');
						resolve()
					}, function(e) {
						console.error('文件夹重命名失败：' + e.message);
					});
				})
			})

		}

		// 调用函数进行文件夹重命名
		await renameFolder(`_doc/${sourceFolder}`, `${destinationFolder}`);
	})
}
// 添加\修改 模块item
/**
 * 创建本地模块
 * @param {string} archivesId - 档案ID
 * @param {string} dictId - 证据链ID
 * @param {string} keyId - 键ID
 * @param {boolean} isAdd - 是否添加
 * @param {Object} form - 表单数据
 */
export async function createLocalNotice(archivesId, dictId, keyId, isAdd, form = {}) {
	const evidenceNoticeFilePath = `${archivesNameBefore}_${archivesId}/evidence_notice.txt`
	const evidenceModuleListFilePath = `${archivesNameBefore}_${archivesId}/getModule.txt`

	let noticeRes = await getFileContextAsync(evidenceNoticeFilePath)
	let noteList = JSON.parse(noticeRes.result)
	let noteItem = noteList.find(item => item.dictId == dictId)
	let noteItemLength = (noteItem.mapList || []).length
	let id;
	console.log(evidenceNoticeFilePath);
	console.log(isAdd);
	if (isAdd) {
		id = !noteItem.mapList.length ? 1 : noteItem.mapList[noteItem.mapList.length - 1].keyId + 1;
	} else {
		id = parseInt(keyId, 10);
	}
	const fileName = `${archivesNameBefore}_${archivesId}/evidence_${dictId}_${id}.txt`
	if (isAdd) {
		noteItem.mapList.push({
			...form,
			keyId: id
		});
	} else {
		noteItem.mapList = noteItem.mapList.map(item => item.keyId === parseInt(keyId, 10) ? {
			...form,
			keyId: id
		} : item);
	}
	let moduleRes = await getFileContextAsync(evidenceModuleListFilePath)
	let moduleList = JSON.parse(moduleRes.result)
	let moduleItem = moduleList.find(item => item.value == dictId)
	if (isAdd && moduleItem) {
		moduleItem.fileNum++;
	}
	// // 添加 notice 下的  mapItem
	// const p1 = writeContextToFileAsync(fileName, form)
	// // noteList 写入
	// const p2 = writeContextToFileAsync(evidenceNoticeFilePath, noteList)
	// // moduleList 写入
	// const p3 = writeContextToFileAsync(evidenceModuleListFilePath, moduleList)
	// await Promise.all([p1, p2, p3])
	console.log(noteList);
	try {
		await Promise.all([
			writeContextToFileAsync(fileName, form),
			writeContextToFileAsync(evidenceNoticeFilePath, noteList),
			...(isAdd && moduleItem ? [writeContextToFileAsync(evidenceModuleListFilePath, moduleList)] : [])
		]);
		return {
			code: 200,
			msg: '操作成功'
		}
	} catch (error) {
		console.error(error);
		return {
			code: 200,
			msg: '操作失败'
		}
	}
}
// 固证 证据链模块item
export async function solidLocalEvidenceItem(archivesId, dictId, keyId, isSolid) {
	const path = `${archivesNameBefore}_${archivesId}/evidence_${dictId}_${keyId}.txt`
	const evidenceNoticePath = `${archivesNameBefore}_${archivesId}/evidence_notice.txt`

	let res = await getFileContextAsync(path)
	let data = JSON.parse(res.result)
	data.stagingStatus = isSolid

	let evidenceRes = await getFileContextAsync(evidenceNoticePath)
	let noteList = JSON.parse(evidenceRes.result)
	let noteItem = noteList.find(item => item.dictId == dictId)
	const list = noteItem.mapList.map(item => {
		if (item.keyId == keyId) {
			return {
				...data,
				keyId
			}
		} else {
			return item
		}
	})
	noteItem.mapList = list
	await writeContextToFileAsync(path, data)
	await writeContextToFileAsync(evidenceNoticePath, noteList)
}
/**
 * 删除 模块item
 * @param {string} archivesId - 档案ID
 * @param {string} dictId - 证据链ID
 * @param {string} keyId - 键ID
 */
export async function removeLocalNoticeItem(archivesId, dictId, keyId) {
	const evidenceNoticePath = `${archivesNameBefore}_${archivesId}/evidence_notice.txt`
	const evidenceModuleListPath = `${archivesNameBefore}_${archivesId}/getModule.txt`
	const fileName = `${archivesNameBefore}_${archivesId}/evidence_${dictId}_${keyId}.txt`

	let noticeRes = await getFileContextAsync(evidenceNoticePath)
	let noteList = JSON.parse(noticeRes.result)
	let noteItem = noteList.find(item => item.dictId == dictId)

	noteItem.mapList = noteItem.mapList.filter(item => item.keyId != keyId)

	let moduleRes = await getFileContextAsync(evidenceModuleListPath)
	let moduleList = JSON.parse(moduleRes.result)
	let moduleItem = moduleList.find(item => item.value == dictId)
	moduleItem.fileNum--


	return new Promise(resolve => {
		plus.io.resolveLocalFileSystemURL('_doc/' + fileName, function(entry) {
			entry.remove(async () => {
				// noteList 写入
				await writeContextToFileAsync(evidenceNoticePath, noteList)
				// moduleList 写入
				await writeContextToFileAsync(evidenceModuleListPath, moduleList)
				resolve()
			})
		}, function(error) {
			console.error('Error resolving directory URL:', error);
		});
	})

}
// 获取证据链item详情
export async function getLocalNotice(archivesId, dictId, keyId) {
	if (keyId === undefined) {

	}
	const fileName = `${archivesNameBefore}_${archivesId}/evidence_${dictId}_${keyId}.txt`
	let currentEntry;
	let directoryEntries = await iterateDierctory()
	for (const entry of directoryEntries) {
		if (entry.name == `${archivesNameBefore}_${archivesId}`) {
			currentEntry = entry
		}
	}
	let flag = await existFileAsync(fileName)
	if (flag) {
		let res = await getFileContextAsync(fileName)
		let data = JSON.parse(res.result)
		return data
	}
}
/**
 * 压缩并上传案卷
 * @param {number | string} archivesId - 案卷id
 */
export async function compressZip(archivesId, userId) {
	const targetPath = `${archivesNameBefore}_${archivesId}`
	// 压缩
	return new Promise(async (resolve, reject) => {
		// let entry = await getFileEntryAsync(`_doc/${targetPath}.zip`)
		// // let entry = await getFileEntryAsync(`_doc/archiveId_1716451395492.zip`)
		// console.log(entry.fullPath);
		// await cutFile(entry)
		// return reject()
		plus.zip.compress(`_doc/${targetPath}`, `_doc/${targetPath}.zip`, async () => {
				let entry = await getFileEntryAsync(`_doc/${targetPath}.zip`)
				// let entry = await getFileEntryAsync(`_doc/archiveId_1716451395492.zip`)
				// console.log(entry.fullPath);
				// await cutFile(entry)
				// return reject()
				uni.uploadFile({
					url: store.state.vuex_config.baseUrl + '/archives/off_line_v2/syncData',
					filePath: entry.fullPath,
					name: 'file',
					header: {
						'content-type': 'multipart/form-data',
					},
					formData: {
						userId
					},
					timeout: 36000000,
					success: (uploadFileRes) => {
						console.log('compressZip');
						const response = JSON.parse(uploadFileRes.data)
						if (response.code == 200) {
							entry.remove(async () => {
								const fileName =
									`${targetPath}${archivesNameAfter}`
								let currentEntry;
								let directoryEntries = await iterateDierctory()
								for (const entry of directoryEntries) {
									if (entry.name == targetPath) {
										currentEntry = entry
									}
								}
								let flag = await existFileAsync(fileName)
								// 更改案卷的案卷id
								let res = await getFileContextAsync(
									fileName)
								let data = JSON.parse(res.result)
								if (flag) {
									// 更改文件夹id 以此关联云端对应案卷id
									if (archivesId != response.data) {
										console.info('需要重新创建新的文件夹');


										const dictArr = await updateArchiveImgUrl(targetPath, response)
										await updateArchiveEvidenceImgUrl(targetPath, response, dictArr)

										data.archivesId = response.data
										await writeContextToFileAsync(fileName, data)
										// 重命名整个案卷文件夹
										await copyFiles(`${targetPath}`, `${archivesNameBefore}_${response.data}`)
									}
									resolve(data)
								}
								uni.showToast({
									title: '上传到服务器成功',
									duration: 1000
								});
							}, () => {
								console.error('error');
							});
						} else {
							uni.showToast({
								icon: 'none',
								title: response.msg
							})
						}
					},
					fail: (e) => {
						console.log('compressZip fail');
						console.error(e);
						// reject(e)
					}

				});

			},
			function(error) {
				console.log('compressZip');
				console.error(error);
				reject(error)
			});
	})
}
/** 更改案卷内所有图片路径 */
async function updateArchiveImgUrl(targetPath, response) {
	// 更改本地文件内所有图片的路径 为云端id
	const noticePath =
		`${targetPath}/evidence_notice.txt`
	let res = await getFileContextAsync(
		noticePath)
	let noticeData = res.result ? JSON.parse(res.result) : []
	let arr = []
	if (noticeData.length) {
		noticeData = noticeData.map(notice => {
			if (notice.mapList && notice.mapList.length) {
				notice.mapList.forEach(item => {
					// 检查是否存在fileList以及fileList是否非空
					if (item.fileList && item.fileList.length) {
						item.fileList = item.fileList.map(file => {
							// 确保file.url是字符串且包含"targetPath"
							if (typeof file.url === 'string' && file.url.includes(targetPath)) {
								arr.push({
									dictId: notice.dictId,
									keyId: item.keyId
								})
								let newStr = file.url.replace(targetPath, `${archivesNameBefore}_${response.data}`);
								return {
									...
									file,
									url: newStr
								}
							}
							// 如果不满足条件，保持原样返回
							return file;
						})
					}
				})
			}
			return notice;
		})
		await writeContextToFileAsync(noticePath, noticeData)
	}

	return arr
}

/** 更改案卷内所有模块的图片路径 */
async function updateArchiveEvidenceImgUrl(targetPath, response, dictArr) {
	const promises = dictArr.map(async item => {
		const url = `_doc/${targetPath}/evidence_${item.dictId}_${item.keyId}.txt`
		let res = await getFileContextAsync(url)

		return {
			url,
			res
		}
	})
	const results = await Promise.all(promises)
	const promises2 = results.map(async resObj => {
		const result = resObj.res.result ? JSON.parse(resObj.res.result) : {}
		const newData = result.fileList.map(file => {
			let newStr = file.url.replace(targetPath, `${archivesNameBefore}_${response.data}`);
			return {
				...file,
				url: newStr
			}
		})
		let fileName2 = resObj.url
		const res2 = await writeContextToFileAsync(fileName2, {
			...result,
			fileList: newData
		})
		return res2
	})
	const results2 = await Promise.all(promises2)
}
/**
 * 解压并下载案卷
 * @param {number | string} archivesId - 案卷id
 */
export function getNetworkDatatoLocal(archivesId) {
	const targetPath = `${archivesNameBefore}_${archivesId}`
	return new Promise((resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			uni.downloadFile({
				url: store.state.vuex_config.baseUrl + '/archives/off_line_v2/getOnLineData' +
					`?archivesId=${archivesId}&dir=${fs.root.fullPath}`,
				headers: {
					'Authorization': store.state.vuex_token
				},
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveFile({
							tempFilePath: res.tempFilePath, //临时路径
							success: function(saveRes) {
								plus.zip.decompress(saveRes.savedFilePath, '_doc/', async () => {
									const fileName =
										`${targetPath}${archivesNameAfter}`
									let currentEntry;
									let directoryEntries = await iterateDierctory()
									for (const entry of directoryEntries) {
										if (entry.name == targetPath) {
											currentEntry = entry
										}
									}
									let flag = await existFileAsync(fileName)
									if (flag) {
										let res =
											await getFileContextAsync(fileName)
										let data = JSON.parse(res.result)
										await writeContextToFileAsync(fileName, data)
										resolve(data)
									}
									getFile(`_doc/${targetPath}.zip`,
										(entry) => {
											entry.remove(
												async () => {},
													() => {})
										})
									uni.showToast({
										title: '下载到本地成功，可以切换到本地使用',
										duration: 1000
									});
								}, (err) => {
									console.error(err);
								});
							}
						})
					}
				}
			});
		}, function(e) {
			console.error(e);
		});
	})
}
/**
 * 更新案卷 updateTime
 * @param {string | number} archivesId - 案卷id
 */
export async function updateArchivesTime(archivesId, time = 0) {
	const path = `${archivesNameBefore}_${archivesId}${archivesNameAfter}`
	let flag = await existFileAsync(path)
	if (flag) {
		let res = await getFileContextAsync(path)
		let data = JSON.parse(res.result)
		let nowFormat = time ? timeFormat(time, 'yyyy-mm-dd hh:MM:ss') : timeFormat(new Date(),
			'yyyy-mm-dd hh:MM:ss')
		data.updateTime = nowFormat
		await writeContextToFileAsync(path, data)
	}
}

/**
 * 创建基础数据
 * @param {object} basicData - 应用的基础数据
 */
export async function saveBasicInfoToPad(basicData) {
	const fileName = 'basicInfo.txt'
	const {
		remoteArchivesList = [], archivesTypeList = {}, userInfoList = [], dictData = {}, allUserList = [],
			templeteList = []
	} = basicData
	let flag = await existFileAsync(fileName)
	if (!flag) {
		await writeContextToFileAsync(fileName, basicData)
	} else {
		let res = await getFileContextAsync(fileName)
		let data = JSON.parse(res.result)
		const localUserList = data.userInfoList || []
		// 使用 Set 数据结构进行去重
		let idSet = new Set();
		let list = localUserList.concat(userInfoList).filter(item => {
			if (idSet.has(item.userId)) {
				return false;
			}
			idSet.add(item.userId);
			return true;
		});
		data = Object.assign(basicData, {
			userInfoList: list
		})
		await writeContextToFileAsync(fileName, data)
	}
}

/**
 * 返回基础数据
 * @return {object} basicData - 应用的基础数据
 */
export async function getBasicInfoFromLocalData() {
	const fileName = 'basicInfo.txt'
	let flag = await existFileAsync(fileName)
	try {
		if (flag) {
			let res = await getFileContextAsync(fileName)
			let data = res.result ? JSON.parse(res.result, (key, value) => {
				if (typeof value === 'string') {
					// 对字符串进行处理
					return value.slice(0, 300); // 只取前 100 个字符
				}
				return value;
			}) : {}
			return data
		} 
		return flag
	} catch (error) {
		console.error(error)
	}
}